package com.atguigu.flink0922.chapter11;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/12 11:09
 */
public class Flink14_Function_Aggregate {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        Table table = tEnv.fromDataStream(waterSensorStream);
        
        // 1. 内联使用
        table
            .groupBy($("id"))
            .select($("id"), call(VcAvg.class, $("vc")))
            .execute()
            .print();
        
        // 2. 注册后使用
        tEnv.createTemporaryFunction("my_avg", VcAvg.class);
        table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")))
            .execute()
            .print();
        
    }
    
    // 累加器类型
    public static class VcAvgAcc {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
    public static class VcAvg extends AggregateFunction<Double, VcAvgAcc> {
        
        // 返回最终的计算结果
        @Override
        public Double getValue(VcAvgAcc accumulator) {
            return accumulator.sum * 1.0 / accumulator.count;
        }
        
        // 初始化累加器
        @Override
        public VcAvgAcc createAccumulator() {
            return new VcAvgAcc();
        }
        
        // 处理输入的值, 更新累加器
        // 参数1: 累加器
        // 参数2,3,...: 用户自定义的输入值
        public void accumulate(VcAvgAcc acc, Integer vc) {
            acc.sum += vc;
            acc.count += 1L;
        }
        
    }
}



